package com.coderush.admin.core.config;

import com.coderush.admin.core.interceptors.AuthInterceptor;
import com.coderush.admin.core.interceptors.RequestInterceptor;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * Web 配置类，注册拦截器
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Resource
    private JwtConfig jwtConfig;
    @Resource
    private RequestInterceptor requestInterceptor;
    @Resource
    private AuthInterceptor authInterceptor;

    /**
     * 跨域配置
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")      // 添加路径规则
                .allowCredentials(true)               // 是否允许在跨域的情况下传递Cookie
                .allowedOriginPatterns("*")           // 允许请求来源的域规则
                .allowedMethods("*")
                .allowedHeaders("*") ;                // 允许所有的请求头
    }

    /**
     * 添加拦截器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 1. 请求拦截器
        registry.addInterceptor(requestInterceptor)
                .addPathPatterns("/**")
                .order(0);

        // 2. 认证拦截器 - 最先执行，拦截所有API请求
        registry.addInterceptor(authInterceptor)
                .addPathPatterns("/**") // 拦截所有请求
                .excludePathPatterns(jwtConfig.getExcludePaths()) // 不需要拦截的请求
                .order(1); // 设置执行顺序，数字越小优先级越高

    }
}